package models

import (
	"github.com/fatih/structs"
	"quantization_trading/src/util"
	"time"
)

//策略信息
type StrategyInfo struct {
	Id int `json:"id"`
	AccountName string `json:"account_name"`
	StrategyName string `json:"strategy_name"` //策略名
	OpenPrice float64 `json:"open_price"`	//开仓价格
	OpenAmount float64 `json:"open_amount"` //开仓总量
	OpenCId string `json:"open_c_id"`	//开仓用户定义id
	ClosePrice float64 `json:"close_price"`	//平仓价格
	CloseAmount float64 `json:"close_amount"` //平仓总量
	CloseCId string `json:"close_c_id"`	//平仓用户定义id
	AllCycle int `json:"all_cycle"`	//	总循环次数
	NewCycle int `json:"new_cycle"`	//当前循环次数
	Side int `json:"side"` // 买卖方向 SELL, BUY
	OpenExecutedQty float64 `json:"open_executed_qty"` //开仓成交数量
	CloseExecutedQty float64 `json:"close_executed_qty"` //平仓成交数量
	StopLoss float64 `json:"stop_loss"` //止损
	StopProfit float64 `json:"stop_profit"`//止盈
	DueTime time.Time `json:"due_time"`	//到期时间
	StatusUse bool `json:"status_use"`		//是否还使用
}


func AddStrategyInfo(strategyInfo *StrategyInfo) (*StrategyInfo,bool){
	var strategy_info_list []StrategyInfo
	db.Where("account_name = ?and strategy_name = ?",strategyInfo.AccountName,strategyInfo.StrategyName).Find(&strategy_info_list)
	if err := db.Create(strategyInfo).Error; err != nil {
		ModelLog.Error(err)
		return nil,false
	}
	return strategyInfo,true
}

func DelStrategyInfo(strategyName, accountName string) int {
	db.Where("account_name = ? and strategy_name = ?",accountName,strategyName).Delete(StrategyInfo{})
	return util.DEL_SUSSESS_STRATEGY
}

func FindAllStrategyInfo() []StrategyInfo {
	var strategy_info_list []StrategyInfo
	db.Find(&strategy_info_list)
	return strategy_info_list
}

func FindByAccountNameStrategyInfo(accountName string) []StrategyInfo {
	var strategy_info_list []StrategyInfo
	db.Where("account_name = ?",accountName).Find(&strategy_info_list)
	return strategy_info_list
}

func FindByAccountNameAndStrategyStrategyInfo(strategyName string, accountName string) ([]StrategyInfo,bool) {
	var strategy_info_list []StrategyInfo
	err := db.Where("account_name = ? and strategy_name =? and status_use =?", accountName, strategyName,true).Find(&strategy_info_list).Error;
	if err != nil {
		return nil,false
	}
	return strategy_info_list,true
}

func FindByAccountNameAndStrategyAndSideStrategyInfo(strategyName string, accountName string,side int) ([]StrategyInfo,bool) {
	var strategy_info_list []StrategyInfo
	err := db.Where("account_name = ? and strategy_name =? and side and status_use =?", accountName, strategyName,side,true).Find(&strategy_info_list).Error;
	if err != nil {
		return nil,false
	}
	return strategy_info_list,true
}

func UpdateStrategyInfo(strategyInfo *StrategyInfo) int {
	strategyInfoMap := structs.Map(strategyInfo)
	db.Model(StrategyInfo{}).Where("id= ?", strategyInfo.Id).Updates(strategyInfoMap)
	//db.Delete(order)
	return util.CLOSE_ORDER_SUSSESS
}